import java.awt.Choice;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import javax.swing.JCheckBox;

public class GUIPanel extends JPanel {
	/* Write the serializable ID */
	private static final long serialVersionUID = 1L;

	/* All the textfields */
	private JTextField txtStationName, txtStationCode, txtTrainName,
			txtSourceStation, txtDestinationStation, txtTrainCode,
			txtStation_1, txtStation_2, txtTrackCode, txtLengthoftrack;

	/* All the labels */
	private JLabel lblStation, lblTrain, lblTrack, lblStationName,
			lblStationCode, lblTrainName, lblDestinationStation,
			lblSourceStation, lblTrainCode, lblStation_1, lblStation_2,
			lblTrackCode, lblLocation, lblLengthOfTrack,
			lblIntermediateStation, lblArrivalTime, lblDepartureTime,
			lblSourceDepartureTime, lblDestinationArrivalTime, lblState,
			lblDays, lblTimeDifference;

	/* All the buttons */
	private JButton btnAddStation, btnAddTrain, btnAddTrack,
			btnDisplayStations, btnDisplayTrains, btnDisplayTrack,
			btnAddIntermediateStation, btnShortestPath;

	/* All the choices */
	Choice chLocation, chStateChoice, chSourceDepartureTimeHours,
			chTimeDifference;
	private Choice chSourceDepartureTimeMinutes, chSourceStation;

	/* Checkboxes */
	private JCheckBox cbTues, cbWed, cbThurs, cbFri, cbMon, cbSat, cbSun;

	/* Object to access the methods of Location Class */
	Location location;

	/* The four hashmaps for storing the trains and stations and the trains */
	HashMap<Integer, Station> stationGraph;
	HashMap<Integer, Train> trainGraph;
	HashMap<Integer, Track> trackGraph;
	/*
	 * The instance of database through which we can do the store and load
	 * operations
	 */
	ObjectContainer db;
	Station st;
	Train train;
	Track track;
	private JTextField txtIntermediatestation;
	private JButton btnClear;
	/* Populatedatabase variable to access the methods */
	PopulateDatabase p;
	int enable;
	/* For intermediate Stations */
	ArrayList<Integer> listOfStationsAdded;
	/* Arraylist for arrival times */
	ArrayList<String> listOfArrivalTimes;
	/* Arraylist for departure times */
	ArrayList<String> listOfDepartureTimes;
	/* Arraylist for running days of the train */
	ArrayList<String> runningDaysOfTheWeek;
	ArrayList<String> tempVariableForStoringDays;

	private JButton btnFinish;
	private Choice chDestinationArrivalTimeHours;
	private Choice chDestinationArrivalTimeMinutes;
	private Choice chArrivalTimeHours;
	private Choice chArrivalTimeMinutes;
	private Choice chDepartureTimeHours;
	private Choice chDepartureTimeMinutes;
	private Choice chDestinationStation;
	private Choice chIntermediateStation;

	private GUIPanel guiPanel;

	/* Constructor */
	public GUIPanel() {
		stationGraph = new HashMap<Integer, Station>();
		trainGraph = new HashMap<Integer, Train>();
		trackGraph = new HashMap<Integer, Track>();
		location = new Location();
		listOfStationsAdded = new ArrayList<Integer>();
		listOfArrivalTimes = new ArrayList<String>();
		listOfDepartureTimes = new ArrayList<String>();
		runningDaysOfTheWeek = new ArrayList<String>();
		tempVariableForStoringDays = new ArrayList<String>();
		try {
			p = new PopulateDatabase();
		} catch (Exception e) {
			e.printStackTrace();
		}

		populateHashMaps();

		createPanel();
		textBoxesEventHandling();
		buttonEventHandling();
		addComponents();
		/* 0 is for AddtrainButton and 1 is for AddIntermedateTrain Button */
		enable = 1;
	}

	public void openDatabase() {
		db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),
				"Routing Management System");
	}

	public void closeDatabase() {
		db.close();
		db = null;
	}

	/* It will retrieve the train object from the database as per the Train code */
	Train retrieveTrainObject(final int trainCode) {
		/* Code to retrieve a particular object */
		@SuppressWarnings("serial")
		List<Train> train = db.query(new Predicate<Train>() {
			public boolean match(Train train) {
				return train.getTrainCode() == trainCode;
			}
		});
		if (train.size() == 0) {
			return null;
		} else {
			Train tr = train.get(0);
			return tr;
		}
	}

	void populateHashMaps() {
		openDatabase();
		/* Code to populate the hash map for stations */
		@SuppressWarnings("serial")
		List<Station> stationList = db.query(new Predicate<Station>() {
			public boolean match(Station station) {
				return station.getStationCode() > 0;
			}
		});
		for (Station station : stationList) {
			stationGraph.put(station.getStationCode(), station);
		}
		/* Code to populate the hash map for trains */
		@SuppressWarnings("serial")
		List<Train> trainList = db.query(new Predicate<Train>() {
			public boolean match(Train train) {
				return train.getTrainCode() > 0;
			}
		});
		for (Train train : trainList) {
			trainGraph.put(train.getTrainCode(), train);
		}

		/* Code to populate the hash map for tracks */
		@SuppressWarnings("serial")
		List<Track> trackList = db.query(new Predicate<Track>() {
			public boolean match(Track track) {
				return track.getTrackCode() > 0;
			}
		});
		for (Track track : trackList) {
			trackGraph.put(track.getTrackCode(), track);
		}
		closeDatabase();
	}

	Station retrieveStationObject(final int stationCode) {

		/* Code to retrieve a particular object */
		@SuppressWarnings("serial")
		List<Station> station = db.query(new Predicate<Station>() {
			public boolean match(Station station) {
				return station.getStationCode() == stationCode;
			}
		});
		// JOptionPane.showMessageDialog(null, "The size of the station = "
		// +station.size());
		Station st = station.get(0);
		return st;
	}

	Track retrieveTrackObject(final int station1, final int station2) {
		@SuppressWarnings("serial")
		List<Track> track1 = db.query(new Predicate<Track>() {
			public boolean match(Track track) {
				return track.getNextStation() == station1
						&& track.getPrevStation() == station2;
			}
		});
		if (track1.size() != 0) {
			Track tr = track1.get(0);
			return tr;
		} else
			return null;
	}

	void insertIntoDatabase(Object object) {
		db.store(object);
	}

	void deleteFromDatabase(Object object) {
		db.delete(object);
	}

	private void createPanel() {
		setBackground(UIManager.getColor("Button.select"));
		setLayout(null);

		/* Top Headings under which the components are there */
		lblStation = new JLabel("STATION");
		lblStation.setBounds(28, 29, 70, 15);

		lblTrain = new JLabel("TRAIN");
		lblTrain.setBounds(291, 29, 70, 15);

		lblTrack = new JLabel("TRACK");
		lblTrack.setBounds(531, 29, 70, 15);

		/* For the Station */
		lblStationName = new JLabel("Station Name");
		lblStationName.setBounds(12, 176, 96, 15);

		lblStationCode = new JLabel("Station Code");
		lblStationCode.setBounds(12, 94, 96, 15);

		txtStationName = new JTextField();
		txtStationName.setBounds(12, 203, 114, 19);
		txtStationName.setColumns(10);

		txtStationCode = new JTextField();
		txtStationCode.setBounds(12, 121, 114, 19);
		txtStationCode.setColumns(10);

		btnAddStation = new JButton("Add Station");

		btnAddStation.setBounds(12, 408, 167, 25);

		/* For the Train */
		lblTrainName = new JLabel("Train Name");
		lblTrainName.setBounds(263, 153, 114, 15);

		txtTrainName = new JTextField();
		txtTrainName.setBounds(250, 174, 114, 19);

		txtTrainName.setColumns(10);

		lblSourceStation = new JLabel("Source Station");
		lblSourceStation.setBounds(263, 199, 114, 15);

		txtSourceStation = new JTextField();
		txtSourceStation.setBounds(247, 219, 130, 19);

		txtSourceStation.setColumns(10);

		lblDestinationStation = new JLabel("Destination Station");
		lblDestinationStation.setBounds(250, 294, 143, 15);

		txtDestinationStation = new JTextField();
		txtDestinationStation.setBounds(250, 321, 143, 19);

		txtDestinationStation.setColumns(10);

		lblTrainCode = new JLabel("Train Code");
		lblTrainCode.setBounds(263, 94, 98, 15);

		txtTrainCode = new JTextField();
		txtTrainCode.setBounds(250, 120, 143, 21);

		txtTrainCode.setColumns(10);

		btnAddTrain = new JButton("Add Train");

		btnAddTrain.setBounds(372, 651, 117, 25);

		/* For the Track */
		lblStation_1 = new JLabel("Station_1");
		lblStation_1.setBounds(487, 94, 80, 15);

		lblStation_2 = new JLabel("Station_2");
		lblStation_2.setBounds(487, 152, 70, 15);

		lblTrackCode = new JLabel("Track Code");
		lblTrackCode.setBounds(487, 211, 114, 15);

		txtStation_1 = new JTextField();
		txtStation_1.setBounds(487, 121, 114, 19);

		txtStation_1.setColumns(10);

		txtStation_2 = new JTextField();
		txtStation_2.setBounds(487, 174, 114, 19);

		txtStation_2.setColumns(10);

		txtTrackCode = new JTextField();
		txtTrackCode.setBounds(487, 232, 114, 19);

		txtTrackCode.setColumns(10);

		btnAddTrack = new JButton("Add Track");

		btnAddTrack.setBounds(487, 408, 117, 25);

		btnDisplayStations = new JButton("Display Stations");

		btnDisplayStations.setBounds(12, 455, 178, 25);

		btnDisplayTrains = new JButton("Display Trains");
		btnDisplayTrains.setBounds(372, 697, 143, 25);

		btnDisplayTrack = new JButton("Display Track");
		btnDisplayTrack.setBounds(487, 455, 154, 25);

		lblLocation = new JLabel("Location");
		lblLocation.setBounds(12, 323, 70, 15);

		chLocation = new Choice();
		chLocation.add("N");
		chLocation.add("E");
		chLocation.add("S");
		chLocation.add("W");
		chLocation.add("C");
		chLocation.add("NE");
		chLocation.add("SE");
		chLocation.add("SW");
		chLocation.add("NW");
		chLocation.setBounds(12, 352, 114, 21);

		/* Label for track length */
		lblLengthOfTrack = new JLabel("Length");
		lblLengthOfTrack.setBounds(487, 256, 70, 15);

		/* Textfield for length of track */
		txtLengthoftrack = new JTextField();
		txtLengthoftrack.setBounds(487, 283, 114, 19);
		txtLengthoftrack.setColumns(10);

		lblIntermediateStation = new JLabel("Intermediate Station 1");
		lblIntermediateStation.setBounds(248, 408, 178, 15);

		txtIntermediatestation = new JTextField();
		txtIntermediatestation.setText("");
		txtIntermediatestation.setBounds(250, 429, 143, 19);
		txtIntermediatestation.setColumns(10);

		btnAddIntermediateStation = new JButton("Add Intermediate Station");
		btnAddIntermediateStation.setBounds(225, 614, 238, 25);

		btnClear = new JButton("Clear");
		btnClear.setBounds(199, 697, 130, 28);

		btnFinish = new JButton("Finish");
		btnFinish.setBounds(202, 651, 117, 25);

		lblArrivalTime = new JLabel("Arrival Time");
		lblArrivalTime.setBounds(250, 460, 143, 15);

		lblDepartureTime = new JLabel("Departure Time");
		lblDepartureTime.setBounds(250, 508, 143, 15);

		lblSourceDepartureTime = new JLabel("Source Departure Time");
		lblSourceDepartureTime.setBounds(250, 250, 176, 15);

		lblDestinationArrivalTime = new JLabel("Destination Arrival time");
		lblDestinationArrivalTime.setBounds(250, 352, 213, 15);

		lblState = new JLabel("State");
		lblState.setBounds(12, 256, 70, 15);

		chStateChoice = new Choice();
		chStateChoice.setBounds(12, 283, 114, 21);
		chStateChoice.add("Andhra Pradesh");
		chStateChoice.add("Karnataka");
		chStateChoice.add("Tamil Nadu");
		chStateChoice.add("Kerala");

		chSourceDepartureTimeHours = new Choice();
		chSourceDepartureTimeHours.setBounds(260, 271, 43, 21);
		for (int i = 0; i < 24; i++)
			chSourceDepartureTimeHours.add(String.valueOf(i));

		chSourceDepartureTimeMinutes = new Choice();
		chSourceDepartureTimeMinutes.setBounds(350, 271, 43, 21);
		for (int i = 0; i < 60; i++)
			chSourceDepartureTimeMinutes.add(String.valueOf(i));

		chDestinationArrivalTimeHours = new Choice();
		chDestinationArrivalTimeHours.setBounds(263, 373, 43, 21);
		for (int i = 0; i < 24; i++)
			chDestinationArrivalTimeHours.add(String.valueOf(i));

		chDestinationArrivalTimeMinutes = new Choice();
		chDestinationArrivalTimeMinutes.setBounds(350, 373, 43, 21);
		for (int i = 0; i < 60; i++)
			chDestinationArrivalTimeMinutes.add(String.valueOf(i));

		chArrivalTimeHours = new Choice();
		chArrivalTimeHours.setBounds(263, 481, 43, 21);
		for (int i = 0; i < 24; i++)
			chArrivalTimeHours.add(String.valueOf(i));

		chArrivalTimeMinutes = new Choice();
		chArrivalTimeMinutes.setBounds(350, 481, 43, 21);
		for (int i = 0; i < 60; i++)
			chArrivalTimeMinutes.add(String.valueOf(i));

		chDepartureTimeHours = new Choice();
		chDepartureTimeHours.setBounds(263, 529, 43, 21);
		for (int i = 0; i < 24; i++)
			chDepartureTimeHours.add(String.valueOf(i));

		chDepartureTimeMinutes = new Choice();
		chDepartureTimeMinutes.setBounds(350, 529, 43, 21);
		for (int i = 0; i < 60; i++)
			chDepartureTimeMinutes.add(String.valueOf(i));

		cbTues = new JCheckBox("Tues");
		cbTues.setBounds(187, 583, 60, 23);

		cbWed = new JCheckBox("Wed");
		cbWed.setBounds(249, 583, 70, 23);

		cbThurs = new JCheckBox("Thurs");
		cbThurs.setBounds(323, 583, 70, 23);

		cbFri = new JCheckBox("Fri");
		cbFri.setBounds(408, 583, 55, 23);

		cbMon = new JCheckBox("Mon");
		cbMon.setBounds(124, 583, 55, 23);

		cbSat = new JCheckBox("Sat");
		cbSat.setBounds(476, 583, 55, 23);

		cbSun = new JCheckBox("Sun");
		cbSun.setBounds(546, 583, 55, 23);

		lblDays = new JLabel("Days");
		lblDays.setBounds(291, 556, 70, 15);

		chSourceStation = new Choice();
		chSourceStation.setBounds(28, 618, 98, 21);
		for (Integer var : getStationGraph().keySet()) {
			chSourceStation.add(getStationGraph().get(var).getStationName());
		}

		chDestinationStation = new Choice();
		chDestinationStation.setBounds(28, 657, 98, 19);
		for (Integer var : getStationGraph().keySet()) {
			chDestinationStation.add(getStationGraph().get(var)
					.getStationName());
		}

		chIntermediateStation = new Choice();
		chIntermediateStation.setBounds(28, 697, 98, 21);
		for (Integer var : getStationGraph().keySet()) {
			chIntermediateStation.add(getStationGraph().get(var)
					.getStationName());
		}

		btnShortestPath = new JButton("Shortest Path");
		btnShortestPath.setBounds(12, 697, 167, 28);

		chTimeDifference = new Choice();
		chTimeDifference.setBounds(546, 697, 70, 21);
		for (int i = 10; i <= 60; i = i + 10)
			chTimeDifference.add(String.valueOf(i));
		chTimeDifference.select(2);

		lblTimeDifference = new JLabel("Time difference");
		lblTimeDifference.setBounds(531, 656, 112, 15);

	}

	private void addComponents() {
		add(lblStation);
		add(lblTrain);
		add(lblTrack);
		add(lblStationName);
		add(lblStationCode);
		add(txtStationName);
		add(txtStationCode);
		add(btnAddStation);
		add(btnAddStation);
		add(lblTrainName);
		add(txtTrainName);
		add(lblSourceStation);
		add(txtSourceStation);
		add(lblDestinationStation);
		add(txtDestinationStation);
		add(lblTrainCode);
		add(txtTrainCode);
		add(btnAddTrain);
		add(lblStation_1);
		add(lblStation_2);
		add(lblTrackCode);
		add(txtStation_1);
		add(txtStation_2);
		add(txtTrackCode);
		add(btnAddTrack);
		add(btnDisplayStations);
		add(btnDisplayTrains);
		add(btnDisplayTrack);
		add(lblLocation);
		add(chLocation);
		add(lblLengthOfTrack);
		add(txtLengthoftrack);
		add(lblIntermediateStation);
		add(txtIntermediatestation);
		add(btnAddIntermediateStation);
		add(btnClear);
		add(btnFinish);
		add(lblArrivalTime);
		add(lblDepartureTime);
		add(lblSourceDepartureTime);
		add(lblDestinationArrivalTime);
		add(lblState);
		add(chStateChoice);
		add(chSourceDepartureTimeHours);
		add(chSourceDepartureTimeMinutes);
		add(chDestinationArrivalTimeHours);
		add(chDestinationArrivalTimeMinutes);
		add(chArrivalTimeHours);
		add(chArrivalTimeMinutes);
		add(chDepartureTimeHours);
		add(chDepartureTimeMinutes);
		add(cbTues);
		add(cbWed);
		add(cbThurs);
		add(cbFri);
		add(cbMon);
		add(cbSat);
		add(cbSun);
		add(lblDays);
		add(btnShortestPath);
		add(chTimeDifference);
		add(lblTimeDifference);

		// add(chSourceStation);
		// add(chDestinationStation);
		// add(chIntermediateStation);
	}

	public void printTrainDetails(Train train) {
		String message = "";
		message = message + "Train Code :"
				+ String.valueOf(train.getTrainCode()) + "\n";
		message = message + "Train Name : " + train.getTrainName() + "\n";
		message = message + "Source Station : " + train.getSourceStation()
				+ "\n";
		message = message + "Source Departure Time : "
				+ train.getSourceDepartureTime() + "\n";
		message = message + "Destination Station : "
				+ train.getDestinationStation() + "\n";
		message = message + "Destination Arrival Time : "
				+ train.getDestinationArrivaltime() + "\n";

		message = message + "Intermediate Stations :";
		for (Integer i : train.getInBetweenStations()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Arrival Times:";
		for (String i : train.getArrivalTimes()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Departure Times:";
		for (String i : train.getDepartureTimes()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Running Days:";
		for (String i : train.getRunningDaysOfTheWeek()) {
			message = message + i + " ";
		}
		message = message + "\n";

		JOptionPane.showMessageDialog(null, message);
	}

	/* Function to validate the time */
	@SuppressWarnings("deprecation")
	boolean validateTime(ArrayList<String> arrivalTimes,
			ArrayList<String> departureTimes, String arrivalTime,
			String departureTime, String sdHours, String sdMinutes,
			String daHours, String daMinutes) {

		String arrivalTimeSplit[], departureTimeSplit[], arrivalTimeHour, arrivalTimeMin, departureTimeHour, departureTimeMin;
		Time tmArrivalTime, tmDepartureTime, tmSourceTime, tmDestinationTime;
		/* Splitting the time so that it is divided into hours and minutes */
		arrivalTimeSplit = arrivalTime.split(":");
		departureTimeSplit = departureTime.split(":");

		/* Assigning the hours and minutes to a Time variable */
		arrivalTimeHour = arrivalTimeSplit[0];
		arrivalTimeMin = arrivalTimeSplit[1];
		tmArrivalTime = new Time(Integer.parseInt(arrivalTimeHour),
				Integer.parseInt(arrivalTimeMin), 0);
		/**************************/

		/* Assigning the hours and minutes to a Time variable */
		departureTimeHour = departureTimeSplit[0];
		departureTimeMin = departureTimeSplit[1];
		tmDepartureTime = new Time(Integer.parseInt(departureTimeHour),
				Integer.parseInt(departureTimeMin), 0);
		/***********************/

		/* Making the source Departure Time and Destination Arrival Time */
		tmSourceTime = new Time(Integer.parseInt(sdHours),
				Integer.parseInt(sdMinutes), 0);
		tmDestinationTime = new Time(Integer.parseInt(daHours),
				Integer.parseInt(daMinutes), 0);

		/*
		 * Checking when the first arrival and departure time is added to the
		 * arraylist
		 */
		if (arrivalTimes.size() == 0 && departureTimes.size() == 0) {
			if (tmArrivalTime.getTime() <= tmSourceTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be less Source Departure Time");
				return true;
			}
			if (tmDepartureTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Departure Time cannot be moe than the Destatination Arrival Time");
				return true;
			}
			if (tmArrivalTime.getTime() >= tmDepartureTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be greater than departure time");
				return true;
			}
			if (tmSourceTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
		}
		/*
		 * Checking when the second onwards arrival and departure time is added
		 * to the arraylist
		 */
		else {
			if (tmSourceTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
			/*
			 * Look we know destination arrival time and we have arrival time
			 * and departure time Now we just need last departure time
			 */
			Time timeOfLastDeparture;
			@SuppressWarnings("unused")
			String lastDepartureTime[], h1, m1, h2, m2;
			/* Converting the last departure time into time */
			lastDepartureTime = listOfDepartureTimes.get(
					listOfDepartureTimes.size() - 1).split(":");
			h1 = lastDepartureTime[0];
			m1 = lastDepartureTime[1];
			timeOfLastDeparture = new Time(Integer.parseInt(h1),
					Integer.parseInt(m1), 0);
			if (tmArrivalTime.getTime() <= timeOfLastDeparture.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Arrival Time can't be less than previous departure time");
				return true;
			}
			if (tmDepartureTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Departure Time cannot be moe than the Destatination Arrival Time");
				return true;
			}
			if (tmArrivalTime.getTime() >= tmDepartureTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be greater than departure time");
				return true;
			}
			if (timeOfLastDeparture.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
		}
		return false;
	}

	/* Function to validate the schedule */
	@SuppressWarnings({ "deprecation" })
	public boolean validateSchedule(String arrivalTime, String departureTime,
			int IntermediateStation, int SourceStation, int DestinationStation,
			ArrayList<Integer> listOfStationsAdded, String sdHours,
			String sdMinutes, String daHours, String daMinutes) {

		String arrivalTimeSplit[], departureTimeSplit[], arrivalTimeHour, arrivalTimeMin, departureTimeHour, departureTimeMin;
		@SuppressWarnings("unused")
		Time tmArrivalTime, tmDepartureTime, tmSourceDepartureTime, tmDestinationArrivalTime;
		/* So here we get the time difference upto 60 minutes */
		int timeDifference = Integer.parseInt(chTimeDifference
				.getSelectedItem());

		/* Splitting the time so that it is divided into hours and minutes */
		arrivalTimeSplit = arrivalTime.split(":");
		departureTimeSplit = departureTime.split(":");

		/* Assigning the hours and minutes to a Time variable */
		arrivalTimeHour = arrivalTimeSplit[0];
		arrivalTimeMin = arrivalTimeSplit[1];
		/* Arrival time of intermediate station */
		tmArrivalTime = new Time(Integer.parseInt(arrivalTimeHour),
				Integer.parseInt(arrivalTimeMin), 0);
		/**************************/

		/* Assigning the hours and minutes to a Time variable */
		departureTimeHour = departureTimeSplit[0];
		departureTimeMin = departureTimeSplit[1];
		/* Departure time of intermediate station */
		tmDepartureTime = new Time(Integer.parseInt(departureTimeHour),
				Integer.parseInt(departureTimeMin), 0);
		/***********************/

		/* Making the source Departure Time and Destination Arrival Time */
		tmSourceDepartureTime = new Time(Integer.parseInt(sdHours),
				Integer.parseInt(sdMinutes), 0);
		tmDestinationArrivalTime = new Time(Integer.parseInt(daHours),
				Integer.parseInt(daMinutes), 0);

		/*
		 * Condition for suppose the intermediate station is the first station
		 * to be added
		 */

		if (listOfStationsAdded.size() == 0) {
			/*
			 * if its the first station then calculate the track Between source
			 * and intermediate
			 */

			for (Integer i : trainGraph.keySet()) {
				Train tr = trainGraph.get(i);
				int j = 0;
				/*
				 * Case where ist two stations of train is same as 1st two
				 * stations of train to be added
				 */
				if (((tr.getSourceStation() == SourceStation && tr
						.getInBetweenStations().get(0) == IntermediateStation))
						&& validateDay(tr)) {
					/* Split the time */
					String str[] = tr.getSourceDepartureTime().split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getArrivalTimes().get(0)
							.split(":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime()
							- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						/*
						 * Enabling the textboxes which were disabled by Add
						 * Intermediate Station Button
						 */
						txtSourceStation.setEnabled(true);
						txtDestinationStation.setEnabled(true);
						chSourceDepartureTimeHours.setEnabled(true);
						chSourceDepartureTimeMinutes.setEnabled(true);
						chDestinationArrivalTimeHours.setEnabled(true);
						chDestinationArrivalTimeMinutes.setEnabled(true);
						chTimeDifference.setEnabled(true);
						return true;
					}
				}
				// JOptionPane.showMessageDialog(null, "adffdgdad");
				/*
				 * Case where last two stations of a train is same as the two
				 * station to be added for new train
				 */
				if (((tr.getInBetweenStations().get(
						tr.getInBetweenStations().size() - 1) == SourceStation && tr
						.getDestinationStation() == IntermediateStation))
						&& validateDay(tr)) {
					JOptionPane.showMessageDialog(
							null,
							"tr.in"
									+ tr.getInBetweenStations().get(
											tr.getInBetweenStations().get(
													tr.getInBetweenStations()
															.size())));
					/* split the time */
					String str[] = tr.getDepartureTimes()
							.get(tr.getDepartureTimes().size() - 1).split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getDestinationArrivaltime().split(
							":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime()
							- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where the two consective stations is in the intermediate
				 * stations
				 */
				for (j = 0; j < tr.getInBetweenStations().size() - 1; j++) {
					if (((tr.getInBetweenStations().get(j) == SourceStation && tr
							.getInBetweenStations().get(j + 1) == IntermediateStation))
							&& validateDay(tr)) {
						/* First ly I split the time */
						String str[] = tr.getDepartureTimes().get(j).split(":"), h1, m1;
						/* Now assigning hour and minute */
						h1 = str[0];
						m1 = str[1];
						/* Now creating the time */
						Time tm = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						/* String for arrival time */
						String strArrival[] = tr.getArrivalTimes().get(j + 1)
								.split(":");
						/* Now assigning hour and minute */
						h1 = strArrival[0];
						m1 = strArrival[1];
						/* Now creating the time */
						Time tmArrival = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						if ((Math.abs(tm.getTime()
								- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
								|| (Math.abs(tmArrival.getTime()
										- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
							JOptionPane.showMessageDialog(
									null,
									"Timing Conflicts with "
											+ tr.getTrainName() + "("
											+ tr.getTrainCode() + ")");
							txtIntermediatestation.setText("");
							chArrivalTimeHours.select(0);
							chArrivalTimeMinutes.select(0);
							chDepartureTimeHours.select(0);
							chDepartureTimeMinutes.select(0);
							return true;
						}
					}
				}
			}
		}
		/* Condition for more than 1 intermediate station */
		else {
			// JOptionPane.showMessageDialog(null,
			// "Inside listof staions greater than zero");
			/*
			 * if its the first station then calculate the track Between source
			 * and intermediate
			 */

			for (Integer i : trainGraph.keySet()) {
				Train tr = trainGraph.get(i);
				int j = 0;
				/*
				 * Case where ist two stations of train is same as 1st two
				 * stations of train to be added
				 */
				if (tr.getSourceStation() == listOfStationsAdded
						.get(listOfStationsAdded.size() - 1)
						&& tr.getInBetweenStations().get(0) == IntermediateStation
						&& validateDay(tr)) {
					/* Split the time */
					String str[] = tr.getSourceDepartureTime().split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					/* Split the time */
					String str1[] = listOfDepartureTimes.get(
							listOfDepartureTimes.size() - 1).split(":");
					/* Now assigning hour and minute */
					h1 = str1[0];
					m1 = str1[1];
					/* Now creating the time */
					Time tm1 = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getArrivalTimes().get(0)
							.split(":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						listOfStationsAdded
								.remove(listOfStationsAdded.size() - 1);
						listOfArrivalTimes
								.remove(listOfArrivalTimes.size() - 1);
						listOfDepartureTimes
								.remove(listOfDepartureTimes.size() - 1);
						/* So that the label constantly changes */
						lblIntermediateStation
								.setText("Intermediate Station "
										+ String.valueOf(listOfStationsAdded
												.size() + 1));
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where last two stations of a train is same as the two
				 * station to be added for new train
				 */
				if (tr.getInBetweenStations()
						.get(tr.getInBetweenStations().size() - 1).intValue() == listOfStationsAdded
						.get(listOfStationsAdded.size() - 1).intValue()
						&& tr.getDestinationStation() == IntermediateStation
						&& validateDay(tr)) {
					// JOptionPane.showMessageDialog(null, "inside second if");
					/* First ly I split the time */
					String str[] = tr.getDepartureTimes()
							.get(tr.getDepartureTimes().size() - 1).split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					/* First ly I split the time */
					String str1[] = listOfDepartureTimes.get(
							listOfDepartureTimes.size() - 1).split(":");
					/* Now assigning hour and minute */
					h1 = str1[0];
					m1 = str1[1];
					/* Now creating the time */
					Time tm1 = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getDestinationArrivaltime().split(
							":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						listOfStationsAdded
								.remove(listOfStationsAdded.size() - 1);
						listOfArrivalTimes
								.remove(listOfArrivalTimes.size() - 1);
						listOfDepartureTimes
								.remove(listOfDepartureTimes.size() - 1);
						/* So that the label constantly changes */
						lblIntermediateStation
								.setText("Intermediate Station "
										+ String.valueOf(listOfStationsAdded
												.size() + 1));
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where the two consective stations is in the intermediate
				 * stations
				 */
				for (j = 0; j < tr.getInBetweenStations().size() - 1; j++) {
					// JOptionPane
					// .showMessageDialog(
					// null,
					// String.valueOf(j)
					// + " "
					// + tr.getInBetweenStations().get(j)
					// + " "
					// + listOfStationsAdded
					// .get(listOfStationsAdded
					// .size() - 1)
					// + " "
					// + " "
					// + tr.getInBetweenStations().get(
					// j + 1) + " "
					// + IntermediateStation);
					int a = tr.getInBetweenStations().get(j);
					int b = listOfStationsAdded
							.get(listOfStationsAdded.size() - 1);
					int c = tr.getInBetweenStations().get(j + 1);
					int d = IntermediateStation;
					/*
					 * if (tr.getInBetweenStations().get(j) ==
					 * listOfStationsAdded .get(listOfStationsAdded.size() - 1)
					 * && tr.getInBetweenStations().get(j + 1) ==
					 * IntermediateStation)
					 */
					// System.out.println(a + b + c + d);
					if (a == b && c == d && validateDay(tr)) {
						// JOptionPane.showMessageDialog(null,
						// "inside third if");
						/* First ly I split the time */
						String str[] = tr.getDepartureTimes().get(j).split(":"), h1, m1;
						/* Now assigning hour and minute */
						h1 = str[0];
						m1 = str[1];
						/* Now creating the time */
						Time tm = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);

						/* First ly I split the time */
						String str1[] = listOfDepartureTimes.get(
								listOfDepartureTimes.size() - 1).split(":");
						/* Now assigning hour and minute */
						h1 = str1[0];
						m1 = str1[1];
						/* Now creating the time */
						Time tm1 = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);

						/* String for arrival time */
						String strArrival[] = tr.getArrivalTimes().get(j + 1)
								.split(":");
						/* Now assigning hour and minute */
						h1 = strArrival[0];
						m1 = strArrival[1];
						/* Now creating the time */
						Time tmArrival = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
								|| (Math.abs(tmArrival.getTime()
										- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
							listOfStationsAdded.remove(listOfStationsAdded
									.size() - 1);
							listOfArrivalTimes
									.remove(listOfArrivalTimes.size() - 1);
							listOfDepartureTimes.remove(listOfDepartureTimes
									.size() - 1);
							/* So that the label constantly changes */
							lblIntermediateStation
									.setText("Intermediate Station "
											+ String.valueOf(listOfStationsAdded
													.size() + 1));
							JOptionPane.showMessageDialog(
									null,
									"Timing Conflicts with "
											+ tr.getTrainName() + "("
											+ tr.getTrainCode() + ")");
							txtIntermediatestation.setText("");
							chArrivalTimeHours.select(0);
							chArrivalTimeMinutes.select(0);
							chDepartureTimeHours.select(0);
							chDepartureTimeMinutes.select(0);
							return true;
						}
					}
				}
			}
		}

		return false;
	}

	public boolean validateDay(Train tr) {
		ArrayList<String> daySelected = new ArrayList<String>();

		if (cbMon.isSelected())
			daySelected.add(cbMon.getText());
		if (cbTues.isSelected())
			daySelected.add(cbTues.getText());
		if (cbWed.isSelected())
			daySelected.add(cbWed.getText());
		if (cbThurs.isSelected())
			daySelected.add(cbThurs.getText());
		if (cbFri.isSelected())
			daySelected.add(cbFri.getText());
		if (cbSat.isSelected())
			daySelected.add(cbSat.getText());
		if (cbSun.isSelected())
			daySelected.add(cbSun.getText());

		int index = 0;
		for (String i : tr.getRunningDaysOfTheWeek()) {
			// if (i.equalsIgnoreCase(daySelected.get(index))) {
			if (daySelected.contains(i)) {
				// JOptionPane.showMessageDialog(null, "days are same " + i +
				// " "
				// + daySelected.get(index));
				return true;
			}
			// index++;
		}
		return false;
	}

	/* To validate the text boxes which come under stations */
	private void textBoxesEventHandling() {
		txtStationCode.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtStationCode.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtStationCode.setText(str2);
					}
				} catch (Exception e1) {
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {
			}
		});

		txtSourceStation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtSourceStation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtSourceStation.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {
			}
		});

		txtDestinationStation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtDestinationStation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtDestinationStation.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtTrainCode.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {

			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtTrainCode.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtTrainCode.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtStation_1.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtStation_1.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtStation_1.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtStation_2.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {

			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtStation_2.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtStation_2.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtTrackCode.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtTrackCode.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtTrackCode.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {
			}
		});

		txtLengthoftrack.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent arg0) {

			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtLengthoftrack.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtLengthoftrack.setText(str2);
					}
				} catch (Exception e1) {
				}
			}

			@Override
			public void keyPressed(KeyEvent arg0) {

			}
		});

		txtIntermediatestation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtIntermediatestation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtIntermediatestation.setText(str2);
					}
				} catch (Exception e1) {
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});
	}

	/* To define the buttons */
	private void buttonEventHandling() {

		/* Event for Adding a Station button */
		btnAddStation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					openDatabase();

					/*
					 * Condition to make sure the text boxes are filled before
					 * submitting
					 */
					if (txtStationName.getText().equals("")
							|| txtStationCode.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All fields must be filled");
						closeDatabase();
						return;
					}
					/* Condition for station to not repeat again once added */
					if (stationGraph.get(Integer.parseInt(txtStationCode
							.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Station Already Exists");
						closeDatabase();
						return;
					}
					/* To create a station object */
					Station station = new Station();
					/* To set the station name */
					station.setStationName(txtStationName.getText());
					/* To store the station code in the station object */
					station.setStationCode(Integer.parseInt(txtStationCode
							.getText()));
					/* To store location of a station i.e it is in SE etc */
					station.setLocation(chLocation.getSelectedItem());
					station.setState(chStateChoice.getSelectedItem());

					/* We are storing the station objects in a hash map */
					stationGraph.put(station.getStationCode(), station);
					/* Inserting into the OODB */
					insertIntoDatabase(station);
					/*****************************************/
					/* Resetting the text boxes to NULL */
					txtStationName.setText("");
					txtStationCode.setText("");
					chLocation.select("N");
					chStateChoice.select("Andhra Pradesh");
					/*****************************************/
					JOptionPane.showMessageDialog(null,
							"Station Successfully Added");
					closeDatabase();
				} catch (Exception e) {
				}
			}
		});

		/* Event for Adding train */
		btnAddTrain.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				try {
					openDatabase();
					/*
					 * Do not allow the button to submit until button is not
					 * enabled
					 */
					if (enable == 1) {
						JOptionPane.showMessageDialog(null,
								"Train Information is incomplete");
						closeDatabase();
						return;
					}
					/*
					 * Condition to make sure the text boxes are filled before
					 * submitting
					 */
					if (txtTrainName.getText().equals("")
							|| txtTrainCode.getText().equals("")
							|| txtSourceStation.getText().equals("")
							|| txtDestinationStation.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All fields must be filled");
						closeDatabase();
						return;
					}

					if (cbMon.isSelected() == false
							&& cbTues.isSelected() == false
							&& cbWed.isSelected() == false
							&& cbThurs.isSelected() == false
							&& cbFri.isSelected() == false
							&& cbSat.isSelected() == false
							&& cbSun.isSelected() == false) {
						JOptionPane.showMessageDialog(null,
								"Atleast one day must be checked");
						closeDatabase();
						return;
					}

					if (txtSourceStation.getText().equals(
							txtDestinationStation.getText())) {
						JOptionPane.showMessageDialog(null,
								"Source is same as Destination");
						closeDatabase();
						return;
					}

					/* Condition for train to not repeat again once added */
					if (trainGraph.get(Integer.parseInt(txtTrainCode.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Train Already Exists");
						closeDatabase();
						return;
					}

					/*
					 * Code to see if Station1 and Station2 exists or not and
					 * store the input in an integer
					 */
					int sourceStation = Integer.parseInt(txtSourceStation
							.getText());
					int destStation = Integer.parseInt(txtDestinationStation
							.getText());

					/* Check whether both stations exist or not */
					if (stationGraph.get(sourceStation) == null
							&& stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Both Station do not exist");
						closeDatabase();
						return;
					}
					/* Check whether the next station is there not */
					if (stationGraph.get(sourceStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Source Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the previous station is there not */
					if (stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Destination Station does not exist");
						closeDatabase();
						return;
					}

					/*
					 * The create Graph method which would give source station
					 * and destination code as input and get the intermediate
					 * stations
					 */
					/*
					 * The code to add intermediate trains by adding shortest
					 * path
					 */

					/* Creating object of train */
					Train train = new Train();

					/*
					 * Inputting the Source destination train_name and train
					 * code
					 */
					train.setTrainName(txtTrainName.getText());
					train.setSourceStation(Integer.parseInt(txtSourceStation
							.getText()));
					train.setDestinationStation(Integer
							.parseInt(txtDestinationStation.getText()));
					train.setTrainCode(Integer.parseInt(txtTrainCode.getText()));
					/* Adding the starting time and ending time */
					train.setSourceDepartureTime(chSourceDepartureTimeHours
							.getSelectedItem()
							+ ":"
							+ chSourceDepartureTimeMinutes.getSelectedItem());
					train.setDestinationArrivaltime(chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem());
					train.setNoOfHalts(listOfStationsAdded.size() + 2);
					/*
					 * Adding the source and destination to the arraylist as the
					 * array list earlier contained only intermediate stations
					 * 
					 * listOfStationsAdded.add(0,
					 * Integer.parseInt(txtSourceStation.getText()));
					 * 
					 * listOfStationsAdded.add(listOfStationsAdded.size(),
					 * Integer.parseInt(txtDestinationStation.getText()));
					 */
					/*
					 * Adding the intermediate stations to the train's list of
					 * stations
					 */

					train.setInBetweenStations(listOfStationsAdded);
					/* Storing the set of arrival times and departure times */
					train.setArrivalTimes(listOfArrivalTimes);
					train.setDepartureTimes(listOfDepartureTimes);
					train.setRunningDaysOfTheWeek(runningDaysOfTheWeek);

					/* Printing the stations for a train */
					/*
					 * String message = ""; for (Integer i :
					 * listOfStationsAdded) message = message +
					 * String.valueOf(i) + " ";
					 * JOptionPane.showMessageDialog(null, message);
					 */

					/* Make the trainGraph */
					trainGraph.put(train.getTrainCode(), train);

					/* Refreshing the text boxes */
					txtTrainName.setText("");
					txtSourceStation.setText("");
					txtDestinationStation.setText("");
					txtTrainCode.setText("");
					txtIntermediatestation.setText("");
					/* refreshing the choices */
					chArrivalTimeHours.select(0);
					chArrivalTimeMinutes.select(0);
					chDepartureTimeHours.select(0);
					chDepartureTimeMinutes.select(0);
					chSourceDepartureTimeHours.select(0);
					chSourceDepartureTimeMinutes.select(0);
					chDestinationArrivalTimeHours.select(0);
					chDestinationArrivalTimeMinutes.select(0);
					chTimeDifference.select(2);
					/* Refreshing the checkbioxes */
					cbMon.setSelected(false);
					cbTues.setSelected(false);
					cbWed.setSelected(false);
					cbThurs.setSelected(false);
					cbFri.setSelected(false);
					cbSat.setSelected(false);
					cbSun.setSelected(false);
					/*****************************/

					/* Inserting into the OODB */
					insertIntoDatabase(train.getInBetweenStations());
					insertIntoDatabase(train.getArrivalTimes());
					insertIntoDatabase(train.getDepartureTimes());
					insertIntoDatabase(train.getRunningDaysOfTheWeek());

					insertIntoDatabase(train);
					printTrainDetails(train);
					/*
					 * Put this train into the station from where it is
					 * originating
					 */
					/***********************************/
					Station st = retrieveStationObject(sourceStation);
					st.getSourceTrains().add(train.getTrainCode());
					insertIntoDatabase(st.getSourceTrains());
					insertIntoDatabase(st);
					/**********************************/
					/*
					 * Put this train into the station to where it is ending
					 */
					/***********************************/
					st = retrieveStationObject(destStation);
					st.getDestinationTrains().add(train.getTrainCode());
					insertIntoDatabase(st.getDestinationTrains());
					insertIntoDatabase(st);
					/**********************************/
					/*
					 * Put this train into the station to where it is
					 * intermediate
					 */
					/**********************************/
					for (Integer i : listOfStationsAdded) {
						st = retrieveStationObject(i);
						st.getIntermediateTrains().add(train.getTrainCode());
						insertIntoDatabase(st.getIntermediateTrains());
						insertIntoDatabase(st);
					}
					/**********************************/
					/*
					 * It will enable the text boxes but at the same time
					 * disable the button
					 */
					txtTrainCode.setEnabled(true);
					txtTrainName.setEnabled(true);
					txtSourceStation.setEnabled(true);
					txtDestinationStation.setEnabled(true);
					txtIntermediatestation.setEnabled(true);
					/* Enabling the choices */
					chSourceDepartureTimeHours.setEnabled(true);
					chSourceDepartureTimeMinutes.setEnabled(true);
					chDestinationArrivalTimeHours.setEnabled(true);
					chDestinationArrivalTimeMinutes.setEnabled(true);
					chArrivalTimeHours.setEnabled(true);
					chArrivalTimeMinutes.setEnabled(true);
					chDepartureTimeHours.setEnabled(true);
					chDepartureTimeMinutes.setEnabled(true);
					chTimeDifference.setEnabled(true);
					/* Enabling the checkboxes */
					cbMon.setEnabled(true);
					cbTues.setEnabled(true);
					cbWed.setEnabled(true);
					cbThurs.setEnabled(true);
					cbFri.setEnabled(true);
					cbSat.setEnabled(true);
					cbSun.setEnabled(true);
					/*
					 * disabling the Addtrain Button and enabling the
					 * Addnexttrain button button after adding into the database
					 */
					enable = 1;
					/*
					 * Since the arraylist of stations was added so not it is
					 * cleared
					 */
					listOfStationsAdded = new ArrayList<Integer>();
					listOfArrivalTimes = new ArrayList<String>();
					listOfDepartureTimes = new ArrayList<String>();
					lblIntermediateStation.setText("Intermediate Station 1");

					closeDatabase();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		/* Event for Adding a track */
		btnAddTrack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					openDatabase();
					/* Code to see that no text box is half filled */
					if (txtStation_1.getText().equals("")
							|| txtStation_2.getText().equals("")
							|| txtTrackCode.getText().equals("")
							|| txtLengthoftrack.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All textfields must be filled");
						closeDatabase();
						return;
					}
					/* Code to make sure track code is not repeated */
					if (trackGraph.get(Integer.parseInt(txtTrackCode.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Track Code Already Used");
						closeDatabase();
						return;
					}

					/*
					 * Code to see if next station exists or not and store the
					 * input in an integer
					 */
					/* nextStation is Station_1 and prevstation is station2 */
					int nextStation = Integer.parseInt(txtStation_1.getText());
					int prevStation = Integer.parseInt(txtStation_2.getText());
					int trackCode = Integer.parseInt(txtTrackCode.getText());

					/* Code to make sure track is not repeated */
					if (trackGraph.get(Integer.parseInt(txtTrackCode.getText())) == null) {
						/*
						 * For loop will go through every track and find if that
						 * already exists or not
						 */
						for (Integer temp : trackGraph.keySet()) {
							if (trackGraph.get(temp).getNextStation() == nextStation
									&& trackGraph.get(temp).getPrevStation() == prevStation) {
								JOptionPane.showMessageDialog(null,
										"Track Already Exists");
								closeDatabase();
								return;
							}
						}
						if (txtStation_1.getText().equals(
								txtStation_2.getText())) {
							JOptionPane.showMessageDialog(null,
									"The two stations have to be distinct");
							closeDatabase();
							return;
						}
					}

					/* Check whether both stations exist or not */
					if (stationGraph.get(nextStation) == null
							&& stationGraph.get(prevStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Both Station do not exist");
						closeDatabase();
						return;
					}
					/* Check whether the next station is there not */
					if (stationGraph.get(nextStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Station 1 does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the previous station is there not */
					if (stationGraph.get(prevStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Station 2 does not exist");
						closeDatabase();
						return;
					}

					/* Creating an object of track */
					Track track1 = new Track();
					Track track2 = new Track();
					/*
					 * Inputting the next station previous station and track
					 * code
					 */
					/* Code to input the parameters of a train object */
					track1.setNextStation(nextStation);
					track1.setPrevStation(prevStation);
					track1.setTrackCode(trackCode);
					track1.setLengthOfTrack(Integer.parseInt(txtLengthoftrack
							.getText()));

					/* Code to input the parameters of a train object */
					track2.setNextStation(prevStation);
					track2.setPrevStation(nextStation);
					track2.setTrackCode(trackCode + 1);
					track2.setLengthOfTrack(Integer.parseInt(txtLengthoftrack
							.getText()));
					/* Code to replicate the same as being done above */
					Station st = retrieveStationObject(stationGraph.get(
							nextStation).getStationCode());
					/*
					 * Checking the details of the station by popping up its
					 * details
					 */

					st.getAdjacentStations().add(prevStation);
					st.getListOfTracks().add(track1.getTrackCode());
					st.getListOfTracks().add(track2.getTrackCode());
					/*
					 * We need to serialize the objects inside objects because
					 * only variables re directly serialized
					 */

					/*
					 * db.store(st.getAdjacentStations());
					 * db.store(st.getTrack1()); db.store(st.getTrack2());
					 */
					insertIntoDatabase(st.getAdjacentStations());
					insertIntoDatabase(st.getListOfTracks());
					// db.store(st);
					insertIntoDatabase(st);
					/*
					 * Code to automatically update the Adjacent stations of a
					 * station after adding a track
					 */
					/*
					 * We will just go that particular object and update that
					 * object's arraylist
					 */

					stationGraph.get(nextStation).getAdjacentStations()
							.add(prevStation);
					/*
					 * Code to insert Track instance into station instance
					 * because of it being an association class
					 */
					stationGraph.get(nextStation).getListOfTracks()
							.add(track1.getTrackCode());
					/*
					 * Code to insert 2nd Track instance into station instance
					 * because of it being an inverse association
					 */
					stationGraph.get(nextStation).getListOfTracks()
							.add(track2.getTrackCode());

					/* Code to retrieve the object for that particular Station */
					st = retrieveStationObject(stationGraph.get(prevStation)
							.getStationCode());
					// JOptionPane.showMessageDialog(null, st.getStationCode());
					st.getAdjacentStations().add(nextStation);
					st.getListOfTracks().add(track1.getTrackCode());
					st.getListOfTracks().add(track2.getTrackCode());
					/*
					 * We need to serialize the objects inside objects because
					 * only variables re directly serialized
					 */
					/*
					 * db.store(st.getAdjacentStations());
					 * db.store(st.getTrack1()); db.store(st.getTrack2());
					 */
					insertIntoDatabase(st.getAdjacentStations());
					insertIntoDatabase(st.getListOfTracks());
					/* Finally we serialize the outside object */
					// db.store(st);
					insertIntoDatabase(st);

					/*
					 * Adding the previous station as adjacent to next station
					 * and next station adjacent to previous station
					 */
					stationGraph.get(prevStation).getAdjacentStations()
							.add(nextStation);

					/*
					 * Code to insert Track instance into station instance
					 * because of it being an association class
					 */
					stationGraph.get(prevStation).getListOfTracks()
							.add(track1.getTrackCode());
					/*
					 * Code to insert 2nd Track instance into station instance
					 * because of it being an inverse association
					 */
					stationGraph.get(prevStation).getListOfTracks()
							.add(track2.getTrackCode());
					/* Code to retrieve the object for that particular Station */
					/* Code to replicate the same as being done above */

					/* Populate the track hash map */
					trackGraph.put(track1.getTrackCode(), track1);
					trackGraph.put(track2.getTrackCode(), track2);
					/* Inserting into the OODB */
					insertIntoDatabase(track1);
					insertIntoDatabase(track2);

					/* Refreshing the text fields */
					txtStation_1.setText("");
					txtStation_2.setText("");
					txtTrackCode.setText("");
					txtLengthoftrack.setText("");
					/* Closing the database */
					JOptionPane.showMessageDialog(null, "Track has been added");
					closeDatabase();
					/*****************************************************************/
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		/* Event for Displaying Stations Button */
		btnDisplayStations.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String message = "";
					/* Printing the object graph */
					for (Integer var : getStationGraph().keySet()) {
						message = message
								+ getStationGraph().get(var).getStationCode()
								+ ": "
								+ getStationGraph().get(var).getStationName()
								+ " ";
						/********************************************************/
						if (stationGraph.get(var).getAdjacentStations().size() > 0)
							message = message + "|Adjacent " + " ";
						for (Integer j : stationGraph.get(var)
								.getAdjacentStations()) {
							message = message + " " + j;
						}
						if (stationGraph.get(var).getAdjacentStations().size() > 0)
							message = message + "| ";
						/********************************************************/
						if (stationGraph.get(var).getSourceTrains().size() > 0)
							message = message + "|Src Trns " + " ";
						for (Integer j : stationGraph.get(var)
								.getSourceTrains()) {
							message = message + " " + j;
						}
						if (stationGraph.get(var).getSourceTrains().size() > 0)
							message = message + "| ";
						/********************************************************/
						if (stationGraph.get(var).getIntermediateTrains()
								.size() > 0)
							message = message + "|Int Trns " + " ";
						for (Integer j : stationGraph.get(var)
								.getIntermediateTrains()) {
							message = message + " " + j;
						}
						if (stationGraph.get(var).getIntermediateTrains()
								.size() > 0)
							message = message + "| ";
						/********************************************************/
						if (stationGraph.get(var).getDestinationTrains().size() > 0)
							message = message + "|Dst Trns " + " ";
						for (Integer j : stationGraph.get(var)
								.getDestinationTrains()) {
							message = message + " " + j;
						}
						if (stationGraph.get(var).getDestinationTrains().size() > 0)
							message = message + "| ";
						/********************************************************/
						message = message + "\n";
					}
					JOptionPane.showMessageDialog(null, message);
				} catch (Exception e) {
				}
			}
		});

		/* Event for Button Displaying Trains */
		btnDisplayTrains.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String message = "";
					for (Integer var : getTrainGraph().keySet()) {

						message = message
								+ getTrainGraph().get(var).getTrainCode()
								+ ": "
								+ getTrainGraph().get(var).getTrainName() + " ";
						// printTrainDetails(getTrainGraph().get(var));
						/*Printing the source station*/
						message = message + "|Src Stn "
								+ trainGraph.get(var).getSourceStation() + "| ";
						/********************************************************/
						if (trainGraph.get(var).getInBetweenStations().size() > 0)
							message = message + "|Int Stns " + " ";
						for (Integer j : trainGraph.get(var)
								.getInBetweenStations()) {
							message = message + " " + j;
						}
						if (trainGraph.get(var).getInBetweenStations().size() > 0)
							message = message + "| ";
						/********************************************************/
						/*Printing the destination station*/
						message = message + "|Dst Stn "
								+ trainGraph.get(var).getDestinationStation() + "| ";
						message = message + "\n";
						
					}
					
					JOptionPane.showMessageDialog(null, message);
				} catch (HeadlessException e) {
				}
			}
		});

		/* Button for Displaying all the tracks */
		btnDisplayTrack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String message = "";
					for (Integer var : getTrackGraph().keySet()) {
						message = message
								+ getTrackGraph().get(var).getTrackCode()
								+ ": "
								+ getTrackGraph().get(var).getNextStation()
								+ " "
								+ getTrackGraph().get(var).getPrevStation()
								+ " "
								+ getTrackGraph().get(var).getLengthOfTrack()
								+ "\n";
					}
					JOptionPane.showMessageDialog(null, message);
				} catch (HeadlessException e) {
				}
			}
		});

		btnAddIntermediateStation.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					openDatabase();
					/* Don't allow any other station to be added */
					/*
					 * If Addnexttrain button is disabled and Addtrain is
					 * enabled then the following condition will be executed
					 */
					if (enable == 0) {
						JOptionPane.showMessageDialog(null,
								"No more stations can be added");
						closeDatabase();
						return;
					}
					/*
					 * Condition to make sure the text boxes are filled before
					 * submitting
					 */
					if (txtTrainName.getText().equals("")
							|| txtTrainCode.getText().equals("")
							|| txtSourceStation.getText().equals("")
							|| txtDestinationStation.getText().equals("")
							|| txtIntermediatestation.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All fields must be filled");
						closeDatabase();
						return;
					}

					if (cbMon.isSelected() == false
							&& cbTues.isSelected() == false
							&& cbWed.isSelected() == false
							&& cbThurs.isSelected() == false
							&& cbFri.isSelected() == false
							&& cbSat.isSelected() == false
							&& cbSun.isSelected() == false) {
						JOptionPane.showMessageDialog(null,
								"Atleast one day must be checked");
						closeDatabase();
						return;
					}
					if (txtSourceStation.getText().equals(
							txtDestinationStation.getText())) {
						JOptionPane.showMessageDialog(null,
								"Source is same as Destination");
						closeDatabase();
						return;
					}

					/* Condition for train to not repeat again once added */
					if (trainGraph.get(Integer.parseInt(txtTrainCode.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Train Already Exists");
						closeDatabase();
						return;
					}

					/*
					 * Code to see if Station1 and Station2 exists or not and
					 * store the input in an integer
					 */
					int sourceStation = Integer.parseInt(txtSourceStation
							.getText());
					int destStation = Integer.parseInt(txtDestinationStation
							.getText());
					int intermediateStation = Integer
							.parseInt(txtIntermediatestation.getText());
					String arrivalTime = chArrivalTimeHours.getSelectedItem()
							+ ":" + chArrivalTimeMinutes.getSelectedItem();
					String departureTime = chDepartureTimeHours
							.getSelectedItem()
							+ ":"
							+ chDepartureTimeMinutes.getSelectedItem();

					/* Check whether both stations exist or not */
					if (stationGraph.get(sourceStation) == null
							&& stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Both Station do not exist");
						closeDatabase();
						return;
					}
					/* Check whether the next station is there not */
					if (stationGraph.get(sourceStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Source Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the previous station is there not */
					if (stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Destination Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the intermediate station is there not */
					if (stationGraph.get(intermediateStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Intermediate Station does not exist");
						closeDatabase();
						return;
					}

					if (intermediateStation == destStation) {
						/* Enable the other Addtrain buttton */
						JOptionPane
								.showMessageDialog(null,
										"Can't be added as an intermediate station as this is the destination station");
						closeDatabase();
						return;
					}

					/*
					 * Incase the station has already been added to the
					 * arraylist
					 */
					if (listOfStationsAdded.contains(intermediateStation)) {
						JOptionPane.showMessageDialog(null,
								"Intermediate Station has already been added");
						closeDatabase();
						return;
					}
					/*
					 * Incase the time for that particular station has already
					 * been added then throw the error
					 */
					if (listOfArrivalTimes.contains(arrivalTime)) {
						JOptionPane.showMessageDialog(null,
								"Arrival Time has already been added");
						closeDatabase();
						return;
					}
					/*
					 * Incase the departure time for that particular station has
					 * already been added then throw the error
					 */
					if (listOfDepartureTimes.contains(departureTime)) {
						JOptionPane.showMessageDialog(null,
								"Departure Time has already been added");
						closeDatabase();
						return;
					}

					/*
					 * Validate if the time is correct and consecutive returns
					 * true if not validating
					 */
					if (validateTime(listOfArrivalTimes, listOfDepartureTimes,
							arrivalTime, departureTime,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						closeDatabase();
						return;
					}

					/*
					 * Validation before adding a station to the train such that
					 * the track does not conflict
					 */
					// JOptionPane.showMessageDialog(null, "asda");
					if (validateSchedule(arrivalTime, departureTime,
							Integer.parseInt(txtIntermediatestation.getText()),
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()),
							listOfStationsAdded,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						// JOptionPane.showMessageDialog(null, "ashjhda");
						closeDatabase();
						return;
					}

					/*
					 * Time to disable the text boxes so that while intermediate
					 * stations are being added the textboxes are locked
					 */
					// JOptionPane.showMessageDialog(null,
					// "Befor disabling fields");
					txtTrainCode.setEnabled(false);
					txtTrainName.setEnabled(false);
					txtSourceStation.setEnabled(false);
					txtDestinationStation.setEnabled(false);
					chSourceDepartureTimeHours.setEnabled(false);
					chSourceDepartureTimeMinutes.setEnabled(false);
					chDestinationArrivalTimeHours.setEnabled(false);
					chDestinationArrivalTimeMinutes.setEnabled(false);
					chTimeDifference.setEnabled(false);
					/* Disabling the checkboxes */
					cbMon.setEnabled(false);
					cbTues.setEnabled(false);
					cbWed.setEnabled(false);
					cbThurs.setEnabled(false);
					cbFri.setEnabled(false);
					cbSat.setEnabled(false);
					cbSun.setEnabled(false);

					/***********************************/

					/* Validation for adding an intermediate station */
					if (listOfStationsAdded.size() == 0)
						/*
						 * if its the first station then calculate the distance
						 * Between source and intermediate
						 */
						track = retrieveTrackObject(sourceStation,
								intermediateStation);
					else
						/*
						 * if the list has 1 value means now compute the
						 * distance with the previous station
						 */
						track = retrieveTrackObject(listOfStationsAdded
								.get(listOfStationsAdded.size() - 1),
								intermediateStation);

					/*
					 * If there is no track then simply return a message saying
					 * track does not exist
					 */
					if (track == null) {
						JOptionPane.showMessageDialog(null,
								"Track does not exist");
						closeDatabase();
						return;
					} else {
						/*
						 * Write the validation for Arrival time and departure
						 * time that they must be consecutive so that before the
						 * intermediate station is added the time for arrival
						 * and departure from that station is verified
						 */
						// JOptionPane.showMessageDialog(null, "Track exists");
						listOfStationsAdded.add(intermediateStation);
						listOfArrivalTimes.add(arrivalTime);
						listOfDepartureTimes.add(departureTime);
						/*
						 * Running a for loop so that we could iterate over all
						 * the checkboxes and see which all are selected
						 */
						if (runningDaysOfTheWeek.size() == 0) {
							if (cbMon.isSelected())
								runningDaysOfTheWeek.add(cbMon.getText());
							if (cbTues.isSelected())
								runningDaysOfTheWeek.add(cbTues.getText());
							if (cbWed.isSelected())
								runningDaysOfTheWeek.add(cbWed.getText());
							if (cbThurs.isSelected())
								runningDaysOfTheWeek.add(cbThurs.getText());
							if (cbFri.isSelected())
								runningDaysOfTheWeek.add(cbFri.getText());
							if (cbSat.isSelected())
								runningDaysOfTheWeek.add(cbSat.getText());
							if (cbSun.isSelected())
								runningDaysOfTheWeek.add(cbSun.getText());
						}
						/* So that the label constantly changes */
						lblIntermediateStation.setText("Intermediate Station "
								+ String.valueOf(listOfStationsAdded.size() + 1));
						/* Displaying the list of stations */
						String message = "";
						for (Integer i : listOfStationsAdded) {
							message = message + String.valueOf(i) + " ";
						}
						// JOptionPane.showMessageDialog(null, message);

						/* Displaying the list of Arrival Times */
						message = "";
						for (String i : listOfArrivalTimes) {
							message = message + i + " ";
						}
						// JOptionPane.showMessageDialog(null, message);
						message = "";

						/* Displaying the list of Departure Times */
						message = "";
						for (String i : listOfDepartureTimes) {
							message = message + i + " ";
						}
						// JOptionPane.showMessageDialog(null, message);
						message = "";

						/*
						 * Making the textbox empty so that next intermediate
						 * station can be added
						 */
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						JOptionPane.showMessageDialog(null,
								"Intermediate Station has been added");
						closeDatabase();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		/*
		 * Clear button enable the intermediate train button and disable the
		 * addtrain button
		 */
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				/* 5 text boxes 8 choices 7 checkboxes 1 label */
				/* Clearing the 5 textfields */
				txtTrainName.setText("");
				txtSourceStation.setText("");
				txtDestinationStation.setText("");
				txtTrainCode.setText("");
				txtIntermediatestation.setText("");

				/* Clearing the 8 choices */
				chSourceDepartureTimeHours.select(0);
				chSourceDepartureTimeMinutes.select(0);
				chDestinationArrivalTimeHours.select(0);
				chDestinationArrivalTimeMinutes.select(0);
				chArrivalTimeHours.select(0);
				chArrivalTimeMinutes.select(0);
				chDepartureTimeHours.select(0);
				chDepartureTimeMinutes.select(0);
				chTimeDifference.select(2);

				/* Clearing the 7 check boxes */
				cbMon.setSelected(false);
				cbTues.setSelected(false);
				cbWed.setSelected(false);
				cbThurs.setSelected(false);
				cbFri.setSelected(false);
				cbSat.setSelected(false);
				cbSun.setSelected(false);

				/* Setting intermediate label to initial */
				lblIntermediateStation.setText("Intermediate Station 1");
				/*
				 * Code to unlock the text boxes in case the data entered is
				 * wrong
				 */
				txtTrainCode.setEnabled(true);
				txtTrainName.setEnabled(true);
				txtSourceStation.setEnabled(true);
				txtDestinationStation.setEnabled(true);
				txtIntermediatestation.setEnabled(true);

				/* Clearing the 8 choices */
				chSourceDepartureTimeHours.setEnabled(true);
				chSourceDepartureTimeMinutes.setEnabled(true);
				chDestinationArrivalTimeHours.setEnabled(true);
				chDestinationArrivalTimeMinutes.setEnabled(true);
				chArrivalTimeHours.setEnabled(true);
				chArrivalTimeMinutes.setEnabled(true);
				chDepartureTimeHours.setEnabled(true);
				chDepartureTimeMinutes.setEnabled(true);
				chTimeDifference.setEnabled(true);

				/* Clearing the 7 check boxes */
				cbMon.setEnabled(true);
				cbTues.setEnabled(true);
				cbWed.setEnabled(true);
				cbThurs.setEnabled(true);
				cbFri.setEnabled(true);
				cbSat.setEnabled(true);
				cbSun.setEnabled(true);

				enable = 1;
				/*
				 * Since we are clearing then we need to clear the intermediate
				 * stations
				 */
				listOfStationsAdded = new ArrayList<Integer>();
				listOfArrivalTimes = new ArrayList<String>();
				listOfDepartureTimes = new ArrayList<String>();
				runningDaysOfTheWeek = new ArrayList<String>();
			}
		});

		/*
		 * Finish button enables the Addtrain button and disables the
		 * Addnexttrain button
		 */
		btnFinish.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				openDatabase();

				if (enable == 0) {
					JOptionPane.showMessageDialog(null,
							"Station List has already been submitted");
					closeDatabase();
					return;
				}

				if (!txtIntermediatestation.getText().equals("")) {
					JOptionPane
							.showMessageDialog(null,
									"Click the Add Intermediate Station Button to Add an Intermediate Station");
					closeDatabase();
					return;
				}

				/* To check if any of the textbox is checked or not */
				if (cbMon.isSelected() == false && cbTues.isSelected() == false
						&& cbWed.isSelected() == false
						&& cbThurs.isSelected() == false
						&& cbFri.isSelected() == false
						&& cbSat.isSelected() == false
						&& cbSun.isSelected() == false) {
					JOptionPane.showMessageDialog(null,
							"Atleast one day must be checked");
					closeDatabase();
					return;
				}

				/*
				 * In case train is only between two stations then the arraylist
				 * of days will be vacant, so need to popoulate that
				 */

				if (runningDaysOfTheWeek.size() == 0) {
					/*
					 * Running a for loop so that we could iterate over all the
					 * checkboxes and see which all are selected
					 */
					if (cbMon.isSelected())
						runningDaysOfTheWeek.add(cbMon.getText());
					if (cbTues.isSelected())
						runningDaysOfTheWeek.add(cbTues.getText());
					if (cbWed.isSelected())
						runningDaysOfTheWeek.add(cbWed.getText());
					if (cbThurs.isSelected())
						runningDaysOfTheWeek.add(cbThurs.getText());
					if (cbFri.isSelected())
						runningDaysOfTheWeek.add(cbFri.getText());
					if (cbSat.isSelected())
						runningDaysOfTheWeek.add(cbSat.getText());
					if (cbSun.isSelected())
						runningDaysOfTheWeek.add(cbSun.getText());
				}

				/*
				 * If arraylist t is not empty we will see if last entry of
				 * arraylist is connected to the destination
				 */
				if (listOfStationsAdded.size() > 0) {

					String arrivalTime = chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem();
					String departureTime = chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem();

					// String
					// arrivalTime=//listOfArrivalTimes.get(listOfArrivalTimes.size()-1);
					// String departureTime
					// =listOfDepartureTimes.get(listOfDepartureTimes.size()-1);

					/*
					 * I changed the first parameter from intermediate textbox
					 * to destination textbox
					 */
					if (validateSchedule(arrivalTime, departureTime,
							Integer.parseInt(txtDestinationStation.getText()),
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()),
							listOfStationsAdded,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						chDestinationArrivalTimeHours.setEnabled(true);
						chDestinationArrivalTimeMinutes.setEnabled(true);
						closeDatabase();
						return;
					}
					String tmDestinationArrivalTime = Integer
							.parseInt(chDestinationArrivalTimeHours
									.getSelectedItem())
							+ ":"
							+ Integer.parseInt(chDestinationArrivalTimeMinutes
									.getSelectedItem());
					String departureTimeSplit[] = departureTime.split(":");

					// if (validateSchedule(
					// tmDestinationArrivalTime,
					// departureTime,
					// Integer.parseInt(txtDestinationStation.getText()),
					// listOfStationsAdded.get(listOfStationsAdded.size() - 1),
					// Integer.parseInt(txtDestinationStation.getText()),
					// listOfStationsAdded, departureTimeSplit[0],
					// departureTimeSplit[1],
					// chDestinationArrivalTimeHours.getSelectedItem(),
					// chDestinationArrivalTimeMinutes.getSelectedItem())) {
					// JOptionPane.showMessageDialog(null,
					// "Destination arrival is same");
					// closeDatabase();
					// return;
					// }

					track = retrieveTrackObject(listOfStationsAdded
							.get(listOfStationsAdded.size() - 1), Integer
							.parseInt(txtDestinationStation.getText()));
					if (track != null) {
						int x = JOptionPane.showConfirmDialog(null,
								"Do you want to add any more station");
						if (x == JOptionPane.NO_OPTION)
							enable = 0;
					} else {
						JOptionPane
								.showMessageDialog(null,
										"Source is not properly connected to the destination");
						closeDatabase();
						return;
					}
				}

				if (listOfStationsAdded.size() == 0) {

					track = retrieveTrackObject(
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()));
					if (track != null) {
						int x = JOptionPane.showConfirmDialog(null,
								"Do you want to add any more station");
						if (x == JOptionPane.NO_OPTION)
							enable = 0;
					} else {
						JOptionPane
								.showMessageDialog(null,
										"Source is not properly connected to the destination");
						closeDatabase();
						return;

					}
				}
				txtTrainCode.setEnabled(false);
				txtTrainName.setEnabled(false);
				txtSourceStation.setEnabled(false);
				txtDestinationStation.setEnabled(false);
				txtIntermediatestation.setEnabled(false);

				chSourceDepartureTimeHours.setEnabled(false);
				chSourceDepartureTimeMinutes.setEnabled(false);
				chDestinationArrivalTimeHours.setEnabled(false);
				chDestinationArrivalTimeMinutes.setEnabled(false);
				chArrivalTimeHours.setEnabled(false);
				chArrivalTimeMinutes.setEnabled(false);
				chDepartureTimeHours.setEnabled(false);
				chDepartureTimeMinutes.setEnabled(false);

				chTimeDifference.setEnabled(false);
				/* Disabling the checkboxes */
				cbMon.setEnabled(false);
				cbTues.setEnabled(false);
				cbWed.setEnabled(false);
				cbThurs.setEnabled(false);
				cbFri.setEnabled(false);
				cbSat.setEnabled(false);
				cbSun.setEnabled(false);
				closeDatabase();
			}
		});

		btnShortestPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Location l = new Location();
				ArrayList<Integer> stations = new ArrayList<Integer>();
				ArrayList<Integer> stations1 = new ArrayList<Integer>();
				ArrayList<Integer> whichStation = new ArrayList<Integer>();
				if (txtSourceStation.getText().equals("")
						|| txtDestinationStation.getText().equals("")) {
					JOptionPane.showMessageDialog(null,
							"Source or Destination missing");
					return;
				}

				stations = l.createGraph(guiPanel,
						Integer.parseInt(txtSourceStation.getText()),
						Integer.parseInt(txtDestinationStation.getText()));

				if (stations == null) {
					JOptionPane.showMessageDialog(null, "Try Again");
					return;
				}

				String str = "";

				stations = modifyStationList(stations,
						Integer.parseInt(txtSourceStation.getText()),
						Integer.parseInt(txtDestinationStation.getText()));

				/*
				 * function to remove those station that have two path to a
				 * station
				 */
				stations = removeRedundantStations(stations);

				/* Code for new section */
				l = new Location();

				stations1 = l.createGraph(guiPanel,
						Integer.parseInt(txtDestinationStation.getText()),
						Integer.parseInt(txtSourceStation.getText()));

				if (stations1 == null) {
					JOptionPane.showMessageDialog(null, "Try Again");
					return;
				}

				String str1 = "";

				stations1 = modifyStationList(stations1,
						Integer.parseInt(txtDestinationStation.getText()),
						Integer.parseInt(txtSourceStation.getText()));

				/*
				 * function to remove those station that have two path to a
				 * station
				 */
				stations1 = removeRedundantStations(stations1);

				for (Integer k : stations) {
					
					str = str + stationGraph.get(k).getStationName() + " " + k
							+ " ";
				}
				JOptionPane.showMessageDialog(null, str);

				createNewGUI(stations);

			}

			private void createNewGUI(ArrayList<Integer> stations){
				GUIFrame1 frame1 = new GUIFrame1(stations);
				
			}
			/* Function to remove those stations that are having two statins */

			private ArrayList<Integer> removeRedundantStations(
					ArrayList<Integer> stations) {
				/* Open the database */
				openDatabase();
				int noOfPaths = 0;
				Station firstStation, adjacentStation;
				Track track;
				int nextStation = 0;
				/* Array list for redundant stations */
				ArrayList<Integer> redundantStations = new ArrayList<Integer>();
				ArrayList<Integer> newListOfstations = new ArrayList<Integer>();

				for (int i = 0; i < stations.size() - 2; i++) {
					/*
					 * first station means suppose station list is 1 2 3 4 5 the
					 * 1 is first station
					 */
					firstStation = stationGraph.get(stations.get(i));
					/* To check if number of paths from a station is more */
					noOfPaths = 0;
					/*
					 * to keep a list of those stations which have multiple
					 * paths from a station as one station should have only one
					 * next station
					 */
					redundantStations = new ArrayList<Integer>();
					for (int j = i + 1; j < stations.size() - 1; j++) {
						nextStation = stations.get(j);
						for (Integer k : firstStation.getAdjacentStations()) {
							if (k.intValue() == j) {
								redundantStations.add(k.intValue());
								noOfPaths++;
								break;
							}
						}

					}
					/*
					 * Suppose we found out that two station can be reached from
					 * a single station, then we process it further
					 */
					if (redundantStations.size() > 1) {
						int min = 100000, stationNumber = 0;
						for (Integer m : redundantStations) {
							/*
							 * just a variable to hold a station object Also it
							 * is adjacet to the station
							 */
							adjacentStation = stationGraph.get(m);
							track = retrieveTrackObject(
									firstStation.getStationCode(),
									adjacentStation.getStationCode());
							/*
							 * We find the track with the minimum distance, and
							 * remove all the others
							 */
							if (min > track.getLengthOfTrack()) {
								min = track.getLengthOfTrack();
								stationNumber = adjacentStation
										.getStationCode();
							}
						}
						for (Integer l : redundantStations) {
							if (l.intValue() != stationNumber)
								stations.remove(l.intValue());
						}
					}
				}
				closeDatabase();
				return stations;
			}

			/*
			 * Function to modify the station list such that the source is at
			 * the beginnin and destination is at the end
			 */
			private ArrayList<Integer> modifyStationList(
					ArrayList<Integer> stations, int source, int destination) {
				int counter = 0, innerCounter = 0, stationNumber = 0, x = 0;
				ArrayList<Integer> temp = new ArrayList<Integer>();
				ArrayList<Integer> newStationList = new ArrayList<Integer>();
				/* Inserting the source into it */
				newStationList.add(source);

				/* Code to copy the stations that are not source or destination */
				for (Integer i : stations) {
					if (i == source || i == destination)
						continue;
					else
						temp.add(i);
				}
				temp.add(0, source);
				temp.add(destination);

				/* Now we will traverse from source to destination on by one */
				/* Storing the size at the beginning itself */
				int size = temp.size();
				// System.out.print("size = " + size + "\n");

				while (newStationList.size() != size - 1) {
					x = newStationList.size() - 1;
					/* To store the number of the station */
					stationNumber = newStationList.get(x);
					// System.out.println("Size =" + newStationList.size()
					// + " Actual Size = " + size + "Station Number = "
					// + stationNumber);
					/* Lookin into the adjacency list */
					for (Integer i : guiPanel.getStationGraph()
							.get(stationNumber).getAdjacentStations()) {
						innerCounter = 0;
						for (Integer j : temp) {
							// System.out.println("Station Number = "
							// + stationNumber + " i " + i + " j " + j);
							// System.out.print(" newStationList.contains(" + i
							// + ") " + newStationList.contains(i) + " ");

							for (Integer k : newStationList) {
								// System.out.print(k.intValue() + " ");
							}
							if (i.intValue() == j.intValue()) {
								if (newStationList.contains(j.intValue()) == false) {
									newStationList.add(j.intValue());
									// System.out.print("Station number "
									// + j.intValue() + " is added\n");
									counter = 1;
									break;
								}
							}
						}
						if (counter == 1) {
							/*
							 * Suppose a station has two station as adjacent,
							 * then we need to get both
							 */
							for (Integer l : guiPanel.getStationGraph()
									.get(stationNumber).getAdjacentStations()) {
								for (Integer m : temp) {
									if (l.intValue() == m.intValue()) {
										if (newStationList.contains(l
												.intValue()) == false) {
											innerCounter = 1;
										}
									}
								}
							}
							if (innerCounter == 1)
								continue;
							else {
								counter = 0;
								break;
							}
						}
					}
				}
				newStationList.add(destination);
				return newStationList;

				// return temp;
			}
		});
	}

	/* To add Components */

	public HashMap<Integer, Station> getStationGraph() {
		return stationGraph;
	}

	public void setStationGraph(HashMap<Integer, Station> stationGraph) {
		this.stationGraph = stationGraph;
	}

	public HashMap<Integer, Train> getTrainGraph() {
		return trainGraph;
	}

	public void setTrainGraph(HashMap<Integer, Train> trainGraph) {
		this.trainGraph = trainGraph;
	}

	public HashMap<Integer, Track> getTrackGraph() {
		return trackGraph;
	}

	public void setTrackGraph(HashMap<Integer, Track> trackGraph) {
		this.trackGraph = trackGraph;
	}

	public GUIPanel getGuiPanel() {
		return guiPanel;
	}

	public void setGuiPanel(GUIPanel guiPanel) {
		this.guiPanel = guiPanel;
	}
}
